package com.oisix.oisystemts2.service.autotask;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.hibernate.Hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.CriteriaSpecification;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.oisix.common.TestData;
import com.oisix.common.TestEnvironment;
import com.oisix.oisystemec.dao.KokyakuDao;
import com.oisix.oisystemec.model.AutoTaskHistory;
import com.oisix.oisystemec.util.SiteCode;
import com.oisix.oisystemfr.persistence.EntityManager;
import com.oisix.oisystemfr.persistence.EntityManagerFactory;
import com.oisix.oisystemfr.util.CsvUtil;

//PointBalanceService.java
public class PointCsvTest {
    private static TestData testData;

    @BeforeClass
    public static void prepare() {
        TestEnvironment.prepare();
        testData = new TestData(
                "src/com/oisix/oisystemts2/service/autotask/PointCsvTest.xls");
        testData.load();
        TimeZone.setDefault(TimeZone.getTimeZone("JST"));

    }

    /**
     * Test001 Method Test: siteCode().
     * 
     * Sub method: autotaskResult().
     * 
     * Test content: output csv file after finishing batch.
     * 
     * Test condition: Gochiflg=0 (oisix)|| Gochiflg=1 (gochi)
     * 
     * Expected Result: create csv file successfully csv file
     * name:pointo_summary.csv content of csv file:91
     */

    @SuppressWarnings("unchecked")
    @Test
    public void testKokyakuDaoGetPointBalance1() {

        PointBalanceService pointBalanceService = new PointBalanceService();

        AutoTaskHistory history = new AutoTaskHistory();
        String userId = "9000";
        pointBalanceService.execute(history, userId);

        // GetsiteCode.
        EntityManager em = EntityManagerFactory.getEntityManager();
        List<Map<String, Object>> resultMap = new ArrayList<Map<String, Object>>();
        StringBuilder sb = new StringBuilder();
        sb.append("select gochi_flg from m_Kokyaku where Gochiflg=0 or Gochiflg=1");

        SQLQuery query = em.createSQLQuery(sb.toString());
        query.addScalar("gochi_flg", Hibernate.STRING);
        resultMap = query.setResultTransformer( CriteriaSpecification.ALIAS_TO_ENTITY_MAP ).list();

        // Confirm Sitecode
        assertThat((String) resultMap.get(0).get("gochi_flg"), is("0"));
        assertThat((String) resultMap.get(4).get("gochi_flg"), is("1"));

        // Get pointBalanceList
        List<Map<String, Object>> pointBalanceList = KokyakuDao.getPointSummaryBalance();

        // Get content of csv file
        try {
            List<String[]> csvContent = CsvUtil.getLines(new File("file/temp_file/pointo_summary.csv"), "UTF-8");
            assertThat(pointBalanceList.size(), is(1));
            assertThat(csvContent.get(0)[0], is("91"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Test002 Method Test: excute().
     * 
     * Sub method: createPointSummaryFile().
     * 
     * Test content: output csv file after finishing batch.
     * 
     * Test condition:N/A
     * 
     * Expected Result: create csv file successfully csv file
     * name:pointo_summary.csv content of csv file:91
     */

    @SuppressWarnings("unchecked")
    @Test
    public void testKokyakuDaoGetPointBalance2() {

        PointBalanceService pointBalanceService = new PointBalanceService();

        AutoTaskHistory history = new AutoTaskHistory();
        String userId = "9000";
        pointBalanceService.execute(history, userId);

        // Get pointBalanceList

        List<Map<String, Object>> pointBalanceList = KokyakuDao
                .getPointSummaryBalance();

        // Get content of csv file
        try {

            List<String[]> csvContent = CsvUtil.getLines(new File("file/temp_file/pointo_summary.csv"), "UTF-8");

            assertThat(csvContent.get(0)[0], is("91"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * Test003 Method Test: excute().
     * 
     * Sub method: createPointSummaryFile().
     * 
     * Test content: output csv file after finishing batch.
     * 
     * Test condition:TORIHIKISAKI_ID=19
     * 
     * Expected Result: create csv file unsuccessfully pointo_summary.csv total
     * content of csv = 91
     * 
     */

    @SuppressWarnings("unchecked")
    @Test
    public void testKokyakuDaoGetPointBalance3() {

        PointBalanceService pointBalanceService = new PointBalanceService();

        AutoTaskHistory history = new AutoTaskHistory();
        String userId = "9000";
        pointBalanceService.execute(history, userId);

        System.out.println("Run this--------");

        // Get TORIHIKISAKI_ID
        EntityManager em = EntityManagerFactory.getEntityManager();
        List<Map<String, Object>> resultMap = new ArrayList<Map<String, Object>>();
        StringBuilder sb = new StringBuilder();
        sb.append("select TORIHIKISAKI_ID from m_Kokyaku");

        System.out.println("Run this--------222222");
        SQLQuery query = em.createSQLQuery(sb.toString());
        query.addScalar("TORIHIKISAKI_ID", Hibernate.STRING);

        resultMap = query.setResultTransformer(
                CriteriaSpecification.ALIAS_TO_ENTITY_MAP).list();

        // Confirm Sitecode
        assertThat(resultMap.get(9).size(), is(1));
        // assertThat((String) resultMap.get(9).get("TORIHIKISAKI_ID"),
        // is("19"));

        // Get pointBalanceList

        List<Map<String, Object>> pointBalanceList = KokyakuDao
                .getPointSummaryBalance();

        // Get content of csv file
        try {

            List<String[]> csvContent = CsvUtil.getLines(new File(
                    "file/temp_file/pointo_summary.csv"), "UTF-8");

            assertThat(csvContent.get(0)[0], is("91"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * Test004 Method Test: excute().
     * 
     * Sub method: createPointSummaryFile().
     * 
     * Test content: output csv file after finishing batch.
     * 
     * Test condition:TORIHIKISAKI_ID=17
     * 
     * Expected Result: create csv file unsuccessfully pointo_summary.csv total
     * content of csv = 91
     * 
     */

    @SuppressWarnings("unchecked")
    @Test
    public void testKokyakuDaoGetPointBalance4() {

        PointBalanceService pointBalanceService = new PointBalanceService();

        AutoTaskHistory history = new AutoTaskHistory();
        String userId = "9000";
        pointBalanceService.execute(history, userId);
        // List

        List<Map<String, Object>> pointBalanceList = KokyakuDao
                .getPointSummaryBalance();

        // Get content of csv file
        try {

            List<String[]> csvContent = CsvUtil.getLines(new File(
                    "file/temp_file/pointo_summary.csv"), "UTF-8");
            assertThat(csvContent.get(0)[0], is("91"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * Test005 Method Test: excute().
     * 
     * Sub method: createPointSummaryFile().
     * 
     * Test content: output csv file after finishing batch.
     * 
     * Test condition:Pointo > 0
     * 
     * Expected Result: create csv file of unsuccessfully pointo_summary.csv
     * total content of csv = 91
     * 
     */

    @SuppressWarnings("unchecked")
    @Test
    public void testKokyakuDaoGetPointBalance5() {

        PointBalanceService pointBalanceService = new PointBalanceService();

        AutoTaskHistory history = new AutoTaskHistory();
        String userId = "9000";
        pointBalanceService.execute(history, userId);
        // List

        List<Map<String, Object>> pointBalanceList = KokyakuDao
                .getPointSummaryBalance();
	
	BigDecimal pointo = (BigDecimal) pointBalanceList.get(0).get('totalPoint');
	String totalPoint = "0";
        if (pointo != null) {
            totalPoint = pointo.toPlainString();
        }

        // Get content of csv file
        try {

            List<String[]> csvContent = CsvUtil.getLines(new File( "file/temp_file/pointo_summary.csv"), "UTF-8");
            
            assertEquals(csvContent.get(0)[0], totalPoint );
            //assertThat(csvContent.get(0)[0], is("91"));


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * Test006 Method Test: Minus between 2 case
     * 
     * Sub method: createPointSummaryFile().
     * 
     * Test content: output csv file after finishing batch.
     * 
     * Test condition: TORIHIKISAKI_ID != 17 , TORIHIKISAKI_ID != 19 , POINTO >
     * 0, GOCHI_FLG = (0:oisix or 1:gochimaru)
     * 
     * Expected Result: create csv file of unsuccessfully pointo_summary.csv
     * 
     * in 1 summarypointo=135 in 2 summarypointo(incasenotmatch)=44
     * 1-2=summarypoint successfull =91
     */
    @SuppressWarnings("unchecked")
    @Test
    public void testKokyakuDaoGetPointBalance6() {

        PointBalanceService pointBalanceService = new PointBalanceService();

        AutoTaskHistory history = new AutoTaskHistory();
        String userId = "9000";
        pointBalanceService.execute(history, userId);
        // List

        List<Map<String, Object>> pointBalanceList = KokyakuDao
                .getPointSummaryBalance();

        // select summary of all excel file

        EntityManager em = EntityManagerFactory.getEntityManager();
        //Object
        List<Map<String, Object>> resultCase = new ArrayList<Map<String, Object>>();
        
        //Sql
        StringBuilder sb = new StringBuilder();
        //Inaert SQL to sb
        sb.append("select SUM(totalPoint) AS totalPoint from m_Kokyaku");

        //Query
        SQLQuery query = em.createSQLQuery(sb.toString());
        //Add field
        query.addScalar("totalPoint", Hibernate.STRING);

        //Query to ObjectResult
        resultCase = query.setResultTransformer( CriteriaSpecification.ALIAS_TO_ENTITY_MAP ).list();

        //new varible int
        int totalPoint1 = resultCase.get(0).get("totalPoint");

        // Confirm
        assertEquals(totalPoint2, 135);
        //assertThat((String) totalPoint1, is("135"));

        // select summary of wrong case in excel file

        // calculate summary pointo of all customer not match sql condition

        //New Sql
        sb = new StringBuilder();
        //Insert SQL to sb
        sb.append("select SUM(pointo) AS totalPoint from m_Kokyaku WHERE torihikisaki_id=17 OR torihikisaki_id=19 OR pointo=0 OR gochiFlg >1");
        //Add field
        query.addScalar("totalPoint", Hibernate.STRING);
        //Query to ObjectResult
        resultCase = query.setResultTransformer( CriteriaSpecification.ALIAS_TO_ENTITY_MAP ).list();
        
        //new varible int
        int totalPoint2 = resultCase.get(0).get("totalPoint");
        // Confirm
        assertEquals(totalPoint2, 44);
        //assertThat((String) totalPoint2, is("44"));

        //Total
        int sumpoint = totalPoint1 - totalPoint2;
        assertEquals( sumpoint , 91 );

        // Get content of csv file (csv reader)
        try {

            List<String[]> csvContent = CsvUtil.getLines(new File(
                    "file/temp_file/pointo_summary.csv"), "UTF-8");
            //assertThat(csvContent.get(0)[0], is((String) sumpoint));
            assertEquals(csvContent.get(0)[0] , sumpoint );

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @AfterClass
    public static void cleanUp() {
        testData.cleanup();
        testData = null;
    }
}